#!/usr/bin/env python3
import pika
import time
import json
from subprocess import Popen, PIPE
import sqlite3

def sendReloadDbMsg(channel):
    commandmsg = 'reload db'
    channel.basic_publish(exchange='',
                          routing_key='DbReloadQueue',
                          body=commandmsg)
    print("msg: ", commandmsg)
    print(" [x] Sent msg out!")


def callback_getcommand(ch, method, properties, body):
    '''
    input: message from passDB manager
    output: message to DBImgQueue
    '''
    print(" [x] Received %r" % body)
    msg = str(body, 'utf-8')

    msgdict = json.loads(msg)
    taskid = msgdict["taskid"]
    option = msgdict["option"]
    url = msgdict["url"]
    faceid = msgdict["faceid"]
    #print("ssssssssssssssss: ", taskid)
    #print("ssssssssssssssss: ", option)
    #print("ssssssssssssssss: ", url)
    #print("ssssssssssssssss: ", faceid)

    imgpath = url # just for temp process!!!!!!..............................
    
    imgspathlist = []
    faceidlist = []
    optionlist = []
    for i in range(1):
        imgspathlist.append(imgpath)
        faceidlist.append(faceid)
        optionlist.append(option)

    dict = {}
    dict.update({'list_imgspath':imgspathlist})
    dict.update({'list_faceids':faceidlist})
    dict.update({'list_options':optionlist})
    commandmsg = json.dumps(dict)

    # 发布消息
    ch.basic_publish(exchange='',
                          routing_key='DbImgpathQueue',
                          body=commandmsg)
    print("msg: ", commandmsg)
    print(" [x] Sent msg out!")

    ch.basic_ack(delivery_tag = method.delivery_tag)


def callback_operatedb(ch, method, properties, body):
    '''
    input: face feature vector
    output: insert face feature vector to db
    '''
    start = time.time()
    print(" [x] Received %r" % body)
    msg = str(body, 'utf-8')
    dict = json.loads(msg)
    list_faceids = dict["list_faceids"]
    list_options = dict["list_options"]
    list_facesfeaturevecs = dict["list_facesfeaturevecs"]

    con = sqlite3.connect("../EP_imgSaveSpace/faceiddatabase.db3")
    cur = con.cursor()
    try:
        cur.execute('CREATE TABLE facedb(face_id TEXT, face_featurevector TEXT PRIMARY KEY)')
        con.commit()
    except:
        print("db is already exists.")

    imgnum = len(list_faceids)
    for i in range(imgnum):
        facenum = len(list_facesfeaturevecs[i])
        for j in range(facenum):
            curfaceid = str(list_faceids[i])
            curfacevec = str(list_facesfeaturevecs[i][j])
            try:
                cur.execute("INSERT INTO facedb(face_id, face_featurevector) VALUES('%s', '%s')" % (curfaceid, curfacevec))
                con.commit()
            except:
                print("current face vector of bbox is already exists.")

    con.close()

    ch.basic_ack(delivery_tag = method.delivery_tag)
    end = time.time()
    print("time cost: ", end - start)


if __name__ == '__main__':
    '''
    发布img imgpath指令至rabbitMQ服务器
    '''
    # 建立连接
    credentials = pika.PlainCredentials('aiot', 'aiot')
    Parameter = pika.ConnectionParameters('127.0.0.1', 5672, '/', credentials)
    connection = pika.BlockingConnection(Parameter)
    channel = connection.channel()

    # 声明/指定消息队列
    channel.queue_declare(queue='DbImgpathQueue')
    channel.queue_declare(queue='DbVecQueue')
    channel.queue_declare(queue='DbReloadQueue')
    channel.queue_declare(queue='PDMoutQueue')

    # 生成img to face feature vector调用指令消息内容,发布消息
    #sendImg2VecMsg(channel)

    # 生成reload database调用指令消息内容,发布消息
    #sendReloadDbMsg(channel)

    # 配置从rabbitMQ服务器消息队列中取消息的参数
    channel.basic_consume(queue='PDMoutQueue', on_message_callback=callback_getcommand)
    channel.basic_consume(queue='DbVecQueue', on_message_callback=callback_operatedb)

    # 断开连接
    #connection.close()

    # 永久持续运行
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

